<template>
  <div class="transport-monitor-container">
    <div class="page-header">
      <div class="header-title">
        <h2>运输监控</h2>
        <span class="subtitle">实时监控车辆位置和运输状态</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="refreshData">
          <el-icon><Refresh /></el-icon>刷新数据
        </el-button>
      </div>
    </div>

    <el-row :gutter="20">
      <!-- 左侧：车辆列表 -->
      <el-col :span="6">
        <el-card class="vehicle-list-card">
          <template #header>
            <div class="card-header">
              <span>车辆列表</span>
              <el-input
                v-model="searchKeyword"
                placeholder="搜索车牌号/司机"
                clearable
                size="small"
                @input="filterVehicles"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </template>
          
          <div class="vehicle-filter">
            <el-radio-group v-model="statusFilter" size="small" @change="filterVehicles">
              <el-radio-button label="all">全部</el-radio-button>
              <el-radio-button label="running">运行中</el-radio-button>
              <el-radio-button label="stopped">已停止</el-radio-button>
              <el-radio-button label="exception">异常</el-radio-button>
            </el-radio-group>
          </div>
          
          <el-scrollbar height="calc(100vh - 280px)">
            <div 
              v-for="vehicle in filteredVehicles" 
              :key="vehicle.id"
              class="vehicle-item"
              :class="{ 'active': selectedVehicle && selectedVehicle.id === vehicle.id }"
              @click="selectVehicle(vehicle)"
            >
              <div class="vehicle-info">
                <div class="vehicle-plate">{{ vehicle.plateNumber }}</div>
                <div class="vehicle-driver">司机: {{ vehicle.driver }}</div>
              </div>
              <div class="vehicle-status">
                <el-tag 
                  :type="getStatusType(vehicle.status)" 
                  size="small"
                >
                  {{ getStatusLabel(vehicle.status) }}
                </el-tag>
                <div class="vehicle-speed">{{ vehicle.speed }} km/h</div>
              </div>
            </div>
          </el-scrollbar>
        </el-card>
      </el-col>
      
      <!-- 右侧：地图和详情 -->
      <el-col :span="18">
        <el-card class="map-card">
          <div class="map-container">
            <!-- 实际应用中这里会集成地图组件 -->
            <div class="map-placeholder">
              <el-empty description="地图加载中...">
                <template #image>
                  <el-icon style="font-size: 60px"><Location /></el-icon>
                </template>
                <template #description>
                  <p>此处将显示车辆实时位置和路线</p>
                  <p v-if="selectedVehicle">当前选中: {{ selectedVehicle.plateNumber }}</p>
                </template>
              </el-empty>
            </div>
          </div>
        </el-card>
        
        <el-card v-if="selectedVehicle" class="detail-card">
          <el-tabs v-model="activeTab">
            <el-tab-pane label="车辆详情" name="vehicle">
              <el-descriptions :column="3" border>
                <el-descriptions-item label="车牌号">{{ selectedVehicle.plateNumber }}</el-descriptions-item>
                <el-descriptions-item label="车辆类型">{{ selectedVehicle.type }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag :type="getStatusType(selectedVehicle.status)">
                    {{ getStatusLabel(selectedVehicle.status) }}
                  </el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="司机">{{ selectedVehicle.driver }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ selectedVehicle.phone }}</el-descriptions-item>
                <el-descriptions-item label="当前速度">{{ selectedVehicle.speed }} km/h</el-descriptions-item>
                <el-descriptions-item label="当前位置" :span="3">{{ selectedVehicle.location }}</el-descriptions-item>
              </el-descriptions>
              
              <div class="vehicle-actions">
                <el-button size="small" @click="handleCall">
                  <el-icon><Phone /></el-icon>呼叫司机
                </el-button>
                <el-button size="small" type="primary" @click="handleMessage">
                  <el-icon><ChatDotRound /></el-icon>发送消息
                </el-button>
                <el-button size="small" type="warning" @click="handleAlarm">
                  <el-icon><AlarmClock /></el-icon>发送警报
                </el-button>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="运输任务" name="task">
              <div v-if="selectedVehicle.currentTask">
                <el-descriptions title="当前任务" :column="2" border>
                  <el-descriptions-item label="计划编号">{{ selectedVehicle.currentTask.planNo }}</el-descriptions-item>
                  <el-descriptions-item label="计划名称">{{ selectedVehicle.currentTask.planName }}</el-descriptions-item>
                  <el-descriptions-item label="开始时间">{{ selectedVehicle.currentTask.startTime }}</el-descriptions-item>
                  <el-descriptions-item label="预计结束时间">{{ selectedVehicle.currentTask.endTime }}</el-descriptions-item>
                  <el-descriptions-item label="订单数量">{{ selectedVehicle.currentTask.orderCount }}</el-descriptions-item>
                  <el-descriptions-item label="总里程">{{ selectedVehicle.currentTask.distance }} km</el-descriptions-item>
                </el-descriptions>
                
                <div class="section-title">订单列表</div>
                <el-table :data="selectedVehicle.currentTask.orders" border style="width: 100%">
                  <el-table-column prop="orderNo" label="订单号" width="150"></el-table-column>
                  <el-table-column prop="fromAddress" label="起始地" min-width="150" show-overflow-tooltip></el-table-column>
                  <el-table-column prop="toAddress" label="目的地" min-width="150" show-overflow-tooltip></el-table-column>
                  <el-table-column prop="status" label="状态" width="100">
                    <template #default="scope">
                      <el-tag :type="getOrderStatusType(scope.row.status)">
                        {{ getOrderStatusLabel(scope.row.status) }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="100">
                    <template #default="scope">
                      <el-button size="small" @click="viewOrderDetail(scope.row)">查看</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
              <el-empty v-else description="当前车辆没有运输任务"></el-empty>
            </el-tab-pane>
            
            <el-tab-pane label="行驶轨迹" name="track">
              <div class="track-filter">
                <el-date-picker
                  v-model="trackDateRange"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD HH:mm"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  @change="loadTrackData"
                ></el-date-picker>
                <el-button type="primary" size="small" @click="loadTrackData">
                  <el-icon><Search /></el-icon>查询
                </el-button>
              </div>
              
              <div class="track-timeline">
                <el-timeline>
                  <el-timeline-item
                    v-for="(track, index) in trackData"
                    :key="index"
                    :timestamp="track.time"
                    :type="getTrackItemType(track.type)"
                  >
                    {{ track.description }}
                    <div class="track-location">位置: {{ track.location }}</div>
                    <div v-if="track.speed" class="track-speed">速度: {{ track.speed }} km/h</div>
                  </el-timeline-item>
                </el-timeline>
              </div>
            </el-tab-pane>
          </el-tabs>
        </el-card>
        
        <el-empty v-else description="请选择一辆车辆查看详情"></el-empty>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  Refresh, 
  Search, 
  Location, 
  Phone, 
  ChatDotRound, 
  AlarmClock 
} from '@element-plus/icons-vue'

const router = useRouter()

// 搜索关键词
const searchKeyword = ref('')

// 状态筛选
const statusFilter = ref('all')

// 选中的车辆
const selectedVehicle = ref(null)

// 当前标签页
const activeTab = ref('vehicle')

// 轨迹时间范围
const trackDateRange = ref([
  new Date(new Date().setHours(0, 0, 0, 0)),
  new Date()
])

// 轨迹数据
const trackData = ref([])

// 车辆数据
const vehicles = ref([
  {
    id: 1,
    plateNumber: '京A12345',
    type: '中型厢式货车',
    driver: '王师傅',
    phone: '13811112222',
    status: 'running',
    speed: 65,
    location: '北京市通州区京哈高速',
    currentTask: {
      planNo: 'TP-2025031501',
      planName: '北京-上海运输计划',
      startTime: '2025-03-15 09:00:00',
      endTime: '2025-03-16 18:00:00',
      orderCount: 2,
      distance: 1200,
      orders: [
        {
          id: 1,
          orderNo: 'TMS-2025031401',
          fromAddress: '北京市朝阳区建国路88号',
          toAddress: '上海市浦东新区张江高科技园区',
          status: 'intransit'
        },
        {
          id: 2,
          orderNo: 'TMS-2025031402',
          fromAddress: '北京市海淀区中关村大街1号',
          toAddress: '上海市黄浦区南京东路1号',
          status: 'assigned'
        }
      ]
    }
  },
  {
    id: 2,
    plateNumber: '京B67890',
    type: '大型厢式货车',
    driver: '李师傅',
    phone: '13833334444',
    status: 'running',
    speed: 72,
    location: '河北省廊坊市京沪高速',
    currentTask: {
      planNo: 'TP-2025031501',
      planName: '北京-上海运输计划',
      startTime: '2025-03-15 11:00:00',
      endTime: '2025-03-16 20:00:00',
      orderCount: 1,
      distance: 1200,
      orders: [
        {
          id: 3,
          orderNo: 'TMS-2025031403',
          fromAddress: '北京市丰台区丰台科技园',
          toAddress: '上海市静安区南京西路1788号',
          status: 'intransit'
        }
      ]
    }
  },
  {
    id: 3,
    plateNumber: '京C13579',
    type: '中型厢式货车',
    driver: '赵师傅',
    phone: '13855556666',
    status: 'stopped',
    speed: 0,
    location: '天津市武清区京津高速服务区',
    currentTask: {
      planNo: 'TP-2025031501',
      planName: '北京-上海运输计划',
      startTime: '2025-03-15 13:00:00',
      endTime: '2025-03-16 22:00:00',
      orderCount: 2,
      distance: 1200,
      orders: [
        {
          id: 4,
          orderNo: 'TMS-2025031404',
          fromAddress: '北京市昌平区回龙观东大街',
          toAddress: '上海市徐汇区虹桥路1号',
          status: 'intransit'
        },
        {
          id: 5,
          orderNo: 'TMS-2025031405',
          fromAddress: '北京市东城区东直门外大街',
          toAddress: '上海市长宁区中山公园',
          status: 'assigned'
        }
      ]
    }
  },
  {
    id: 4,
    plateNumber: '京D24680',
    type: '冷藏车',
    driver: '钱师傅',
    phone: '13877778888',
    status: 'exception',
    speed: 0,
    location: '河北省保定市京港澳高速',
    currentTask: {
      planNo: 'TP-2025031502',
      planName: '北京-广州运输计划',
      startTime: '2025-03-15 08:00:00',
      endTime: '2025-03-17 18:00:00',
      orderCount: 1,
      distance: 2200,
      orders: [
        {
          id: 6,
          orderNo: 'TMS-2025031406',
          fromAddress: '北京市大兴区经济开发区',
          toAddress: '广州市天河区天河路385号',
          status: 'intransit'
        }
      ]
    }
  },
  {
    id: 5,
    plateNumber: '京E97531',
    type: '大型厢式货车',
    driver: '孙师傅',
    phone: '13899990000',
    status: 'running',
    speed: 68,
    location: '河北省石家庄市京港澳高速',
    currentTask: null
  }
])

// 筛选后的车辆列表
const filteredVehicles = computed(() => {
  let result = vehicles.value

  // 状态筛选
  if (statusFilter.value !== 'all') {
    result = result.filter(vehicle => vehicle.status === statusFilter.value)
  }

  // 关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    result = result.filter(vehicle => 
      vehicle.plateNumber.toLowerCase().includes(keyword) || 
      vehicle.driver.toLowerCase().includes(keyword)
    )
  }

  return result
})

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    'running': 'success',
    'stopped': 'info',
    'exception': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status) => {
  const statusMap = {
    'running': '运行中',
    'stopped': '已停止',
    'exception': '异常'
  }
  return statusMap[status] || '未知'
}

// 获取订单状态类型
const getOrderStatusType = (status) => {
  const statusMap = {
    'pending': 'info',
    'confirmed': 'primary',
    'assigned': 'warning',
    'intransit': 'success',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取订单状态标签
const getOrderStatusLabel = (status) => {
  const statusMap = {
    'pending': '待审核',
    'confirmed': '已确认',
    'assigned': '已分配',
    'intransit': '运输中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取轨迹项类型
const getTrackItemType = (type) => {
  const typeMap = {
    'start': 'primary',
    'normal': 'info',
    'stop': 'warning',
    'exception': 'danger'
  }
  return typeMap[type] || 'info'
}

// 筛选车辆
const filterVehicles = () => {
  // 已通过计算属性实现
}

// 选择车辆
const selectVehicle = (vehicle) => {
  selectedVehicle.value = vehicle
  activeTab.value = 'vehicle'
  
  // 加载轨迹数据
  if (trackDateRange.value) {
    loadTrackData()
  }
}

// 刷新数据
const refreshData = () => {
  // 实际应用中应该调用API刷新数据
  ElMessage.success('数据已刷新')
  
  // 模拟更新车辆数据
  vehicles.value.forEach(vehicle => {
    if (vehicle.status === 'running') {
      // 随机更新速度
      vehicle.speed = Math.floor(60 + Math.random() * 20)
    }
  })
}

// 呼叫司机
const handleCall = () => {
  if (!selectedVehicle.value) return
  
  ElMessage.success(`正在呼叫 ${selectedVehicle.value.driver}，电话：${selectedVehicle.value.phone}`)
}

// 发送消息
const handleMessage = () => {
  if (!selectedVehicle.value) return
  
  ElMessage.success(`已向 ${selectedVehicle.value.driver} 发送消息`)
}

// 发送警报
const handleAlarm = () => {
  if (!selectedVehicle.value) return
  
  ElMessage.warning(`已向 ${selectedVehicle.value.driver} 发送警报信息`)
}

// 查看订单详情
const viewOrderDetail = (order) => {
  router.push(`/order/detail/${order.id}`)
}

// 加载轨迹数据
const loadTrackData = () => {
  if (!selectedVehicle.value || !trackDateRange.value) return
  
  // 实际应用中应该调用API获取轨迹数据
  // 这里使用模拟数据
  trackData.value = [
    {
      time: '2025-03-15 09:00:00',
      type: 'start',
      description: '开始运输任务',
      location: '北京市朝阳区建国路88号',
      speed: 0
    },
    {
      time: '2025-03-15 09:30:00',
      type: 'normal',
      description: '正常行驶',
      location: '北京市朝阳区京通快速路',
      speed: 60
    },
    {
      time: '2025-03-15 10:15:00',
      type: 'normal',
      description: '正常行驶',
      location: '北京市通州区京哈高速',
      speed: 75
    },
    {
      time: '2025-03-15 11:00:00',
      type: 'stop',
      description: '临时停车',
      location: '北京市通州区京哈高速服务区',
      speed: 0
    },
    {
      time: '2025-03-15 11:30:00',
      type: 'normal',
      description: '继续行驶',
      location: '北京市通州区京哈高速',
      speed: 70
    },
    {
      time: '2025-03-15 12:45:00',
      type: 'normal',
      description: '正常行驶',
      location: '河北省廊坊市京沪高速',
      speed: 80
    },
    {
      time: '2025-03-15 13:30:00',
      type: 'exception',
      description: '车辆故障',
      location: '河北省廊坊市京沪高速',
      speed: 0
    },
    {
      time: '2025-03-15 14:15:00',
      type: 'normal',
      description: '故障排除，继续行驶',
      location: '河北省廊坊市京沪高速',
      speed: 65
    }
  ]
}

// 定时刷新数据
let refreshInterval = null

onMounted(() => {
  // 设置定时刷新
  refreshInterval = setInterval(() => {
    // 实际应用中应该调用API获取最新数据
    // 这里只是简单模拟
    vehicles.value.forEach(vehicle => {
      if (vehicle.status === 'running') {
        // 随机更新速度
        vehicle.speed = Math.floor(60 + Math.random() * 20)
      }
    })
  }, 30000) // 每30秒刷新一次
})

onBeforeUnmount(() => {
  // 清除定时器
  if (refreshInterval) {
    clearInterval(refreshInterval)
  }
})
</script>

<style scoped>
.transport-monitor-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.vehicle-filter {
  margin: 10px 0 15px;
}

.vehicle-list-card {
  height: calc(100vh - 140px);
}

.vehicle-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: background-color 0.3s;
}

.vehicle-item:hover {
  background-color: #f5f7fa;
}

.vehicle-item.active {
  background-color: #ecf5ff;
}

.vehicle-plate {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.vehicle-driver {
  font-size: 13px;
  color: #606266;
}

.vehicle-status {
  text-align: right;
}

.vehicle-speed {
  font-size: 13px;
  color: #606266;
  margin-top: 5px;
}

.map-card {
  margin-bottom: 20px;
}

.map-container {
  height: 500px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.map-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.detail-card {
  min-height: 300px;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0 15px;
  color: #303133;
}

.vehicle-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.track-filter {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.track-timeline {
  padding: 10px;
  max-height: 400px;
  overflow-y: auto;
}

.track-location {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.track-speed {
  font-size: 12px;
  color: #409EFF;
  margin-top: 3px;
}
</style>
